/*
 * @Author: hx 2542123711@QQ.com
 * @Date: 2024-12-23 19:53:24
 * @LastEditors: hx 2542123711@QQ.com
 * @LastEditTime: 2024-12-24 20:28:33
 * @FilePath: /class_socket/udp_socket/client.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<cstdlib>
#include <strings.h>
#include<unistd.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<sys/socket.h>
#include"log.hpp"
#include <arpa/inet.h>

#define BUFFERSIZE 4096

using namespace std;

Log log;

void Uage()
{
    cout << "Please Enter: cmd ip" << endl;
}

//可以使用命令行参数来告诉服务端的ip和port
// ./client serverip port
int main(int argc, char* argv[])
{

    if(argc != 3)
    {
        Uage();
        exit(0);
    }

    //char*
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    struct sockaddr_in server;
    socklen_t len = sizeof(server);
    bzero(&server, len);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    //2.绑定ip和端口号: client不用认为的绑定端口号，OS会自动帮我们绑定, 在client首次发送数据的时候OS会给我们bind

    //1.创建套接字文件udp socket
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        log(Fatal, "socket file create fail:%d, %s\n", errno, strerror(errno));
        exit(1);
    }

    string message;
    char buffer[BUFFERSIZE];

    while(true)
    {
        //3. 发送数据
        cout << "Please Enter@ ";
        getline(cin, message);

        ssize_t m = sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&server, len);
        if(m < 0)
        {
            log(Fatal, "send fail...:%d, %s\n", errno, strerror(errno));
            exit(2);
        }

        struct sockaddr_in tmp;
        socklen_t lentmp = sizeof(tmp);

        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&tmp, &lentmp);
        if(n > 0)
        {
            buffer[n] = 0;
            cout << buffer <<endl;
        }
        
    }

    return 0;
}

